package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.model.Article;
import com.example.forum.model.Board;
import com.example.forum.model.User;
import com.example.forum.services.IArticleService;
import com.example.forum.services.IBoardService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: TODO
 * @Author Mr.Tang
 */
@Api(tags = "关于帖子的相关接口")
@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Resource
    private IArticleService articleService;

    @Resource
    private IBoardService boardService;

    /**
     *  发布新帖子
     * @param boardId 版块Id
     * @param title 帖子标题
     * @param content 帖子内容
     * @return 结果
     */
    @ApiOperation("发布新帖")
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @ApiParam("版块ID") @RequestParam("boardId") @NonNull Long boardId,
                            @ApiParam("帖子标题") @RequestParam("title") @NonNull String title,
                            @ApiParam("帖子内容") @RequestParam("content") @NonNull String content) {
        // 校验用户是否禁言
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            // 已禁言
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 版块校验
        Board board = boardService.selectById(boardId);
        if (board == null || board.getDeleteState() == 1 || board.getState() == 1) {
            log.warn(ResultCode.Failed_BOARD_BANNED.toString());
            return AppResult.failed(ResultCode.Failed_BOARD_BANNED);
        }
        // 封装帖子对象
        Article article = new Article();
        article.setTitle(title);
        article.setContent(content);
        article.setBoardId(boardId);
        article.setUserId(user.getId());
        // 调用service
        articleService.create(article);
        return AppResult.success("发布成功！");
    }


    @ApiOperation("获取帖子列表")
    @GetMapping("/getArticleList")
    public AppResult<List<Article>> getArticleList(@ApiParam("版块Id") @RequestParam(value = "boardId",required = false) Long boardId) {

        // 定义一个返回的结果集
        List<Article> articles = new ArrayList<>();
        // 查询
        if (boardId == null) {
            articles = articleService.selectAll();
        }else {
            articles = articleService.selectAllByBoardId(boardId);
        }
        // 结果是否为空
        if (articles == null) {
            // 如果结果集为空，那么创建一个空数组
            articles = new ArrayList<>();
        }
        // 响应结果
        return AppResult.success(articles);
    }


    @ApiOperation("根据帖子获取帖子详情")
    @GetMapping("/details")
    public AppResult<Article> getDetails(HttpServletRequest request,
                                         @ApiParam("帖子ID") @RequestParam("id") @NonNull Long id) {
        // 从session中获取当前登录的用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        // 调用service，获取帖子详情
        Article article = articleService.selectDetailById(id);
        // 非空判断
        if (article == null) {
            return AppResult.failed(ResultCode.FAILED_NOT_EXISTS);
        }
        // 判断当前用户是否为作者
        if (user.getId() == article.getUserId()) {
            // 标识为作者
            article.setOwn(true);
        }
        // 正确返回
        return AppResult.success(article);
    }


    @ApiOperation("修改帖子")
    @PostMapping("/modify")
    public AppResult modify(HttpServletRequest request,
                            @ApiParam("帖子id") @RequestParam("id") @NonNull Long id,
                            @ApiParam("帖子标题") @RequestParam("title") @NonNull String title,
                            @ApiParam("帖子正文") @RequestParam("content") @NonNull String content) {
         // 获取当前登录的用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 校验用户状态
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 查询帖子的详情
        Article article = articleService.selectById(id);
        if (article == null) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        // 判断是否为作者
        if (user.getId() != article.getUserId()) {
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }
        // 判断帖子的状态 - 已归档或删除
        if (article.getState() == 1 || article.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.Failed_ARTICLE_BANNED);
        }

        // 调用service
        articleService.modify(id, title, content);
        log.info("帖子更新成功！");
        // 正确返回
        return AppResult.success();
    }


    @ApiOperation("点赞")
    @PostMapping("/likeUp")
    public AppResult likeUp(HttpServletRequest request,
                            @ApiParam("帖子Id") @RequestParam("id") @NonNull Long id) {
        // 校验用户状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 判断用户是否处于正常状态
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 调用service
        articleService.likeUpById(id);
        // 正确返回
        return AppResult.success();
    }


    @ApiOperation("删除帖子")
    @PostMapping("/delete")
    public AppResult deleteById(HttpServletRequest request,
                                @ApiParam("帖子Id") @RequestParam("id") @NonNull Long id) {
        // 校验用户状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 查询帖子详情
        Article article = articleService.selectById(id);
        if (article == null || article.getDeleteState() == 1) {
            // 帖子不存在或已删除
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        // 判断当前用户是否为作者
        if (user.getId() != article.getUserId()) {
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }
        // 调用service
        articleService.deleteById(id);
        // 返回结果
        return AppResult.success();
    }


    @ApiOperation("获取用户的帖子列表")
    @GetMapping("/getAllByUserId")
    public AppResult<List<Article>> getAllByUserId(HttpServletRequest request,
                                                   @ApiParam("用户Id") @RequestParam(value = "userId",required = false) Long userId) {
        // 若 userid 为空，从session获取用户对象
        if (userId == null) {
            HttpSession session = request.getSession(false);
            User user = (User) session.getAttribute(AppConfig.USER_SESSION);
            userId = user.getId();
        }
        // 调用service
        List<Article> list = articleService.selectByUserId(userId);
        // 返回结果
        return AppResult.success(list);

    }


}
